<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="emit('update:visible', $event)"
    :title="title"
    width="80%"
    class="vectorized-content-dialog"
  >
    <!-- 文档信息卡片 -->
    <el-card v-if="content" class="document-info">
      <template #header>
        <div class="card-header">
          <h3>{{ content.documentInfo.title }}</h3>
          <el-tag>{{ content.documentInfo.type }}</el-tag>
        </div>
      </template>
      <div class="info-stats">
        <div class="stat-item">
          <div class="label">向量化时间</div>
          <div class="value">{{ formatDate(content.documentInfo.vectorizedAt) }}</div>
        </div>
        <div class="stat-item">
          <div class="label">总片段数</div>
          <div class="value">{{ content.summary.totalChunks }}</div>
        </div>
        <div class="stat-item">
          <div class="label">总字数</div>
          <div class="value">{{ content.summary.totalWords }}</div>
        </div>
        <div class="stat-item">
          <div class="label">平均片段大小</div>
          <div class="value">{{ content.summary.averageChunkSize }} 字符</div>
        </div>
      </div>
    </el-card>

    <!-- 片段列表 -->
    <div v-if="content" class="chunks-container">
      <div class="chunks-header">
        <h3>文档片段</h3>
        <div class="chunks-actions">
          <el-switch v-model="showFullContent" active-text="显示完整内容" />
        </div>
      </div>
      
      <el-table 
        v-loading="loading"
        :data="content.chunks" 
        stripe 
        style="width: 100%"
      >
        <el-table-column label="序号" width="80">
          <template #default="{ row }">
            <span class="chunk-index">{{ row.index }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="内容">
          <template #default="{ row }">
            <div class="chunk-text">
              <div v-if="showFullContent" class="full-content">{{ row.content }}</div>
              <div v-else class="preview-content">
                {{ row.preview }}
                <el-button link type="primary" @click="showFullContent = true">
                  显示更多
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="统计" width="200">
          <template #default="{ row }">
            <div class="chunk-stats">
              <el-tag size="small">{{ row.stats.characters }} 字符</el-tag>
              <el-tag size="small" type="success">{{ row.stats.words }} 词</el-tag>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加分页器 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="content.pagination.total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <el-empty v-else description="未找到向量化内容" />

    <template #footer>
      <span class="dialog-footer">
        <el-button 
          type="danger" 
          :loading="deleting"
          @click="handleDelete"
        >
          删除向量化内容
        </el-button>
        <el-button @click="emit('update:visible', false)">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { getVectorizedContent, deleteVectorizedContent } from '@/api/documents'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  visible: {
    type: Boolean,
    required: true
  },
  document: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:visible', 'deleted'])
const deleting = ref(false)

// 分页相关状态
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const content = ref(null)
const showFullContent = ref(false)

// 处理页码改变
const handlePageChange = async (page) => {
  currentPage.value = page
  await fetchContent()
}

// 处理每页条数改变
const handleSizeChange = async (size) => {
  pageSize.value = size
  currentPage.value = 1
  await fetchContent()
}

// 监听对话框显示状态和文档变化
watch(
  [() => props.visible, () => props.document],
  async ([newVisible, newDoc], [oldVisible]) => {
    if (newVisible && (!oldVisible || newDoc?.id)) {
      currentPage.value = 1
      await fetchContent()
    }
  },
  { immediate: true }
)

// 获取内容
const fetchContent = async () => {
  if (!props.document?.id || !props.visible) return
  
  loading.value = true
  try {
    const { data } = await getVectorizedContent(props.document.id, {
      page: currentPage.value,
      pageSize: pageSize.value
    })
    content.value = data
    
    // 添加调试日志
    console.log('Fetched content:', data)
  } catch (error) {
    ElMessage.error('获取向量化内容失败')
    console.error('Failed to fetch content:', error)
  } finally {
    loading.value = false
  }
}

// 计算标题
const title = computed(() => 
  `向量化内容 - ${props.document?.title || ''}`
)

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 删除向量化内容
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该文档的向量化内容吗？删除后需要重新向量化。',
      '删除确认',
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        confirmButtonClass: 'el-button--danger'
      }
    )

    deleting.value = true
    await deleteVectorizedContent(props.document.id)
    ElMessage.success('向量化内容已删除')
    // 更新父组件中的文档状态
    emit('deleted', props.document.id)
    emit('update:visible', false)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete vectorized content:', error)
      ElMessage.error('删除向量化内容失败')
    }
  } finally {
    deleting.value = false
  }
}
</script>

<style lang="scss" scoped>
.vectorized-content-dialog {
  :deep(.el-dialog__body) {
    padding: 20px;
  }
}

.document-info {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  h3 {
    margin: 0;
    font-size: 18px;
  }
}

.info-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-top: 10px;
}

.stat-item {
  text-align: center;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;

  .label {
    color: #666;
    font-size: 14px;
  }

  .value {
    font-size: 24px;
    font-weight: bold;
    margin-top: 5px;
    color: var(--el-color-primary);
  }
}

.chunks-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.chunks-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h3 {
    margin: 0;
    font-size: 18px;
  }
}

.chunk-text {
  padding: 10px 0;
}

.preview-content {
  color: #666;
  display: flex;
  align-items: center;
  gap: 10px;
}

.full-content {
  white-space: pre-wrap;
  line-height: 1.5;
}

.chunk-stats {
  display: flex;
  gap: 8px;
}

.chunk-index {
  font-weight: bold;
  color: var(--el-color-primary);
}

:deep(.el-table) {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f5f7fa;
}

:deep(.el-table__header) {
  font-weight: bold;
}

:deep(.el-table__row) {
  transition: all 0.3s ease;

  &:hover {
    background-color: var(--el-color-primary-light-9) !important;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}
</style> 